import React, { useEffect, useState } from 'react'
import { Card, Form, Select, Input, Space, Button, Table, Image } from 'antd'
import { ColumnsType } from 'antd/lib/table';
import { changeState, getDictList, getHospitalList } from '@/api/hospital/hospitalList';
import { IDictList, IHospitalItem, IHospitalList, IHospitalListFields, IHospitalListParams } from '@/api/hospital/model/hospitalListTypes';
import { useNavigate } from 'react-router-dom';
const { Option } = Select;
export default function HospitalList() {
    // navigate
    const navigate = useNavigate()
    // form对象
    const [form] = Form.useForm()
    // 声明状态
    let [province, setProvince] = useState<IDictList>([]);// 省列表
    let [cities, setCities] = useState<IDictList>([]);//市列表
    let [region, setRegion] = useState<IDictList>([]);//区列表
    let [hosTypeList, setHosTypeList] = useState<IDictList>([]);//医院等级列表
    // 分页相关状态
    let [page, setPage] = useState<number>(1)
    let [pageSize, setPageSize] = useState<number>(5)
    let [total, setTotal] = useState<number>(10)

    let [hospitals, setHospitals] = useState<IHospitalList>([])
    // loading
    let [loading, setLoading] = useState<boolean>(false)
    // 声明表单数据状态
    let [fields, setFields] = useState<IHospitalListFields>({
        hoscode: undefined,
        hosname: undefined,
        provinceCode: undefined,
        hostype: undefined,
        cityCode: undefined,
        districtCode: undefined,
        status: undefined
    });

    const columns: ColumnsType<IHospitalItem> = [
        {
            title: '序号',
            width: 60,
            align: 'center',
            render(value: any, row: any, index: number) {
                return (page - 1) * pageSize + (index + 1)
            }
        },
        {
            title: '医院logo',
            width: 100,
            render(row: IHospitalItem) {
                return <Image
                    width={100}
                    src={'data:image/png;base64,' + row.logoData}
                />
            }
        },
        {
            title: '医院名称',
            dataIndex: 'hosname'
        },
        {
            title: '等级',
            render(row: IHospitalItem) {
                return row.param.hostypeString
            }
        },
        {
            title: '详细地址',
            render(row: IHospitalItem) {
                return row.param.fullAddress
            }
        },
        {
            title: '状态',
            render(row: IHospitalItem) {
                return row.status ? '已上线' : '未上线'
            }
        },
        {
            title: '创建时间',
            dataIndex: 'createTime'
        },
        {
            title: '操作',
            render(row: IHospitalItem) {
                return (
                    <Space>
                        <Button type="primary" onClick={()=>navigate('/syt/hospital/hospitalList/show/' + row.id)}>查看</Button>
                        <Button type="primary" onClick={()=>navigate('/syt/hospital/hospitalList/schedule/' + row.hoscode)}>排班</Button>
                        <Button type="primary" onClick={()=>_changeStata(row.id, row.status)}>{row.status ? '下线' : '上线'}</Button>
                    </Space>
                )
            }
        }
    ]
    /**
     * 点击上下线切换状态
     * @param id 
     * @param status 
     */
    async function _changeStata(id:string, status:number){
        // 以前是上线的转改变为下线，下线的改为上线
        status = status === 1 ? 0 : 1;
        await changeState(id, status)
        // 刷新列表
        _getHospitalList();
    }
    /**
     * 获取省列表
     */
    async function getProvince() {
        // 获取省数据
        let data = await getDictList("86")
        // 设置省状态
        setProvince(data);
    }
    /**
     * 省改变，获取市列表数据
     */
    async function getCities(value: string) {
        // 根据省id获取市的列表
        let data = await getDictList(value);
        // 设置市列表状态
        setCities(data);
        // 清空市表单的值和区表单的值
        form.setFieldsValue({
            cityCode: undefined,
            districtCode: undefined
        })
        // 重置区列表的状态
        setRegion([])
    }
    /**
     * 市改变获取区
     */
    async function getRegion(value: string) {
        let data = await getDictList(value);
        setRegion(data);
        // 重置 区表单值为undefined
        form.setFieldsValue({
            districtCode: undefined
        })
    }
    /**
     * 获取医院等级列表 10000
     */
    async function getHosTypeList() {
        let data = await getDictList("10000");
        // 设置医院等级列表状态
        setHosTypeList(data)
    }
    /**
     * 获取医院列表数据
     */
    async function _getHospitalList() {
        // 改变loading
        setLoading(true);
        let { content, totalElements } = await getHospitalList({ page, limit: pageSize, ...fields });
        // 设置医院状态和总条数
        setHospitals(content)
        setTotal(totalElements)
        // 关闭loading
        setLoading(false);
    }
    /**
     * 点击查询按钮触发
     */
    async function searchHandler() {
        console.log('search');
        console.log(form.getFieldsValue());
        setFields(form.getFieldsValue());
    }

    async function clear() {
        // 清空表单数据
        form.setFieldsValue({
            hoscode: undefined,
            hosname: undefined,
            provinceCode: undefined,
            hostype: undefined,
            cityCode: undefined,
            districtCode: undefined,
            status: undefined
        })
        // 清空状态
        setFields({
            hoscode: undefined,
            hosname: undefined,
            provinceCode: undefined,
            hostype: undefined,
            cityCode: undefined,
            districtCode: undefined,
            status: undefined
        })
        // 
        page !== 1 && setPage(1)
    }
    useEffect(() => {
        // 获取省
        getProvince();
        // 获取医院等级
        getHosTypeList();
    }, [])

    useEffect(() => {
        _getHospitalList()
    }, [page, pageSize, fields?.hosname, fields?.hoscode, fields?.provinceCode, fields?.cityCode, fields?.districtCode, fields?.hostype, fields?.status])
    return (
        <Card>
            <Form
                form={form}
                layout='inline'
                onFinish={searchHandler}
            >
                <Form.Item name='provinceCode'>
                    <Select onChange={getCities} className='mb20' style={{ width: 120 }} placeholder='请选择省'>
                        {province.map(item => (
                            <Option key={item.id} value={item.value}>{item.name}</Option>
                        ))}

                    </Select>
                </Form.Item>
                <Form.Item name='cityCode'>
                    <Select onChange={getRegion} style={{ width: 120 }} placeholder='请选择市'>
                        {cities.map(city => (
                            <Option key={city.id} value={city.value}>{city.name}</Option>
                        ))}

                    </Select>
                </Form.Item>
                <Form.Item name='districtCode'>
                    <Select style={{ width: 120 }} placeholder='请选择区'>
                        {region.map(item => (
                            <Option key={item.id} value={item.value}>{item.name}</Option>
                        ))}

                    </Select>
                </Form.Item>
                <Form.Item name='hosname'>
                    <Input placeholder='医院名称' />
                </Form.Item>
                <Form.Item name='hoscode'>
                    <Input placeholder='医院编号' />
                </Form.Item>
                <Form.Item name='hostype'>
                    <Select style={{ width: 120 }} placeholder='医院类型'>
                        {hosTypeList.map(item => (
                            <Option key={item.id} value={item.value}>{item.name}</Option>
                        ))}

                    </Select>
                </Form.Item>
                <Form.Item name='status'>
                    <Select style={{ width: 120 }} placeholder='医院状态'>
                        <Option value={0}>未上线</Option>
                        <Option value={1}>已上线</Option>
                    </Select>
                </Form.Item>
                <Form.Item>
                    <Space>
                        <Button htmlType='submit' type='primary' loading={loading}>查询</Button>
                        <Button disabled={Object.values(fields as IHospitalListParams).every(item => item === undefined)} onClick={clear}>清空</Button>
                    </Space>
                </Form.Item>
            </Form>

            <Table
                loading={loading}
                className='mt'
                columns={columns}
                dataSource={hospitals}
                rowKey='id'
                pagination={{
                    current: page,
                    pageSize,
                    total,
                    showQuickJumper: true,
                    showSizeChanger: true,
                    pageSizeOptions: [5, 10, 20],
                    onChange(page: number, pageSize: number) {
                        setPage(page)
                        setPageSize(pageSize)
                    }
                }}
            />
        </Card>
    )
}
